import router from './index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store/index'
import error from '@/views/error/error'
const whitelist = ['/login']
NProgress.configure({ showSpinner: false })
router.beforeEach(async (to, _, next) => {
  store.commit('updateHistory', to)
  NProgress.start()
  /** addroute & 权限校验逻辑 */
  if (to.path !== '/login' && store.getters.token) {
    /** 是否存在用户信息 */
    if (!store.getters.roles) {
      await store.dispatch('InfoApi')
      await store.dispatch('RoutesApi')
      router.addRoute(store.getters.addRoutes)
      router.addRoute({ path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('@/views/error/error') })
      next({ ...to, replace: true })
    }
    /** 拿到用户信息保证路由加载完成直接渲染 */
    else next()
  }
  /** 白名单不跳转Login 直接进入 */
  else whitelist.indexOf(to.path) !== -1 ? next() : next('/login')
})

router.afterEach((to) => {
  NProgress.done()
  const title = to.meta.title ? to.meta.title : to.name
  document.title = title + ' Vue Admin Tsx'
})
